from enum import Enum
from typing import Any, Tuple, List, Union


class BaseEnum(str, Enum):
    """枚举基类，提供通用方法"""

    @classmethod
    def to_list(cls) -> List[Tuple[Any, ...]]:
        """将枚举转换为列表形式

        子类需要重写此方法，返回格式为：
        - 二元组: [(枚举值, 显示名称), ...]
        - 三元组: [(枚举值, 显示名称, 额外代码), ...]
        """
        raise NotImplementedError("子类必须实现 to_list 方法")

    @classmethod
    def get_name(cls, key: str) -> str:
        """根据枚举键获取显示名称

        Args:
            key: 枚举键值

        Returns:
            对应的显示名称，找不到时返回空字符串
        """
        items = cls.to_list()
        if not items:
            return ""

        # 根据元组长度处理不同格式
        item_length = len(items[0]) if items else 0

        if item_length == 2:
            return next((v for k, v in items if k == key), "")
        elif item_length >= 3:
            return next((v for k, v, *extra in items if k == key), "")
        else:
            return ""

    @classmethod
    def get_extra_field(cls, key: str, field_index: int = 2) -> Any:
        """获取额外字段的值

        Args:
            key: 枚举键值
            field_index: 额外字段的索引，默认第3个位置

        Returns:
            对应的额外字段值，找不到时返回None
        """
        items = cls.to_list()
        if not items or field_index < 2:
            return None

        for item in items:
            if item[0] == key and len(item) > field_index:
                return item[field_index]
        return None

    @classmethod
    def get_all_keys(cls) -> List[str]:
        """获取所有枚举键"""
        return [item[0] for item in cls.to_list()]

    @classmethod
    def get_all_names(cls) -> List[str]:
        """获取所有显示名称"""
        items = cls.to_list()
        if not items:
            return []

        item_length = len(items[0])
        if item_length == 2:
            return [v for k, v in items]
        elif item_length >= 3:
            return [v for k, v, *extra in items]
        else:
            return []

    @classmethod
    def is_valid_key(cls, key: str) -> bool:
        """检查键是否有效"""
        return key in cls.get_all_keys()
